/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on a sample project from CommonsWare, LLC
 * From _The Busy Coder's Guide to Advanced Android Development_
 *		http://commonsware.com/AdvAndroid
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.ContentData;
import edu.bsu.android.gtv.apps.bconnected.objects.Content;
import edu.bsu.android.gtv.apps.bconnected.util.Adapters;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
 
/**
 * Display a list of tech tips from the database
 * @author Kyle Parker, University Computing Services
 */
public class ContentFragment extends ListFragment {
    private static final String TAG = "ContentFragment";
    private ViewGroup mRootView;
    private View mLoadingSpinner;
    private Activity mActivity;
    private ArrayList<Content> mContent;
    private Adapters.ContentAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivity = getActivity();             
        loadContent();  
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_list_with_spinner, null); 
        // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are
        // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity.
    	mRootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

        mLoadingSpinner = mRootView.findViewById(R.id.loading_spinner); 
        mLoadingSpinner.setVisibility(View.VISIBLE);
        
        return mRootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    /** {@inheritDoc} */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	// DONE: On click, open the web browser to view the full content
        Content content = (Content) getListView().getItemAtPosition(position);
        
        if (content != null) {
        	Intent intent = new Intent(Intent.ACTION_VIEW);
        	intent.setData(Uri.parse(content.getFullStoryURL().toString()));
        	startActivity(intent);
        }
    }

    /**
     * Load the web posts from the service handler into the array adapter
     * During the load, the activity will display a spinner/loading graphic so the user knows something is happening behind the scenes
     */
    private void loadContent() {
        mContent = new ArrayList<Content>();
        mAdapter = new Adapters.ContentAdapter(mActivity, R.layout.list_item, mContent);
        setListAdapter(this.mAdapter);

        Runnable load = new Runnable(){
            public void run() {
            	try {
	            	ContentData.initializeContent(mActivity);
	    	    	
	            	if (ContentData.getContentCount() > 0) {
	            		mContent = ContentData.getContent();
	            	}
	            	
	        		mActivity.runOnUiThread(returnTerm);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread =  new Thread(null, load, "loadContent");
        thread.start();
    }
    
    /**
     * Add each term object from the service handler to the array adapter and set the visibility of the spinner to "gone"
     */
    private Runnable returnTerm = new Runnable(){
        public void run() {
            if (mContent != null && mContent.size() > 0){
                for(int i=0; i < mContent.size(); i++)
                {
                	mAdapter.add(mContent.get(i));
                }
            }

            mLoadingSpinner.setVisibility(View.GONE);
            mAdapter.notifyDataSetChanged();
        }
    };
}
